<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class AdminIdentity extends CUserIdentity {
	/**
	 * Authenticates a user.
	 * The example implementation makes sure if the username and password
	 * are both 'demo'.
	 * In practical applications, this should be changed to authenticate
	 * against some persistent user identity storage (e.g. database).
	 * against some persistent user identity storage (e.g. database).
	 * @return boolean whether authentication succeeds.
	 */
	public $response = '';
	protected $_identity = '';
	public $login_method = 0;
	
	public function authenticate() {
		try {
			$passport = new PassportApi ( 'admin' );
            $this->login_method=trim($this->login_method);
            $this->username=trim($this->username);
            $this->password=trim($this->password);
			$rs = $passport->loginAccount ( $this->login_method, $this->username, $this->password );
			$logAttributes = array(
                          'userid'=>'^^userid',
						  'username'     =>'^^username',
                          'runtime'=>'^^request_time',
                          'ip'      =>'^^ip',
                          'event_type'=>'后台登陆',
                          'page'    =>'^^action',
                          'sta'     =>'^^sta',
		                  'usertype'        =>'^^usertype'
			);
			if ($rs) {
				
				$data = $passport->getPassportCachedUserDataByTickets ( $passport->tickets );//从护照中心获得所有缓存数据
				/**
				if (! isset ( $data [WebUserD::STORAGE_KEY] [WebUserD::PREFIX_KEY_ADMIN] ) || ! is_array ( $data [WebUserD::STORAGE_KEY] [WebUserD::PREFIX_KEY_ADMIN] ) || count ( $data [WebUserD::STORAGE_KEY] [WebUserD::PREFIX_KEY_ADMIN] ) < 1) {
					$admin = new Admin ();
					$account = $admin->find ( "username=:username", array (":username" => $this->username ) );
				} else {
					$account = new Admin ();
					$account->setAttributes ( $data [WebUserD::STORAGE_KEY] [WebUserD::PREFIX_KEY_ADMIN], false );
				}**/
				$admin = new Admin ();
				$account = $admin->find ( "username=:username", array (":username" => $this->username ) );
				if (is_null ( $account )) {
					return UtilD::handleResult ( 0, '用户名错误！' );
				}
				if ($account->sta == '0') {
					return UtilD::handleResult ( 0, '此账号已被冻结！' );
				}
				$this->_identity = $account->id;
				$states = array ('tickets' => $passport->tickets, 'login_method' => $this->login_method );
				$this->setPersistentStates ( $states );
				$account->update_time = time ();
				if(empty($data ['currentIP'])){
					 $data ['currentIP']=Yii::App ()->request->getUserHostAddress ();
				}
				$mflag=(isset($data ['lastip']) && $data ['lastip']=== Yii::App ()->request->getUserHostAddress ());
				$account->setIsNewRecord ( false );
				$logAttributes['userid']=(int)$account->id;
				$logAttributes['username']=$account->username;
				$account->login_nums=$logAttributes['login_nums']=++$account->login_nums;
				$account->last_loginip=$logAttributes['last_loginip']=$data ['currentIP'];
				$account->last_logintime=$logAttributes['last_logintime']=time();
				
				$clearTime=UtilD::getCache('user', 'clearExpireLoginLogTime');
				if($clearTime===false){
					UtilD::setCache('user', 'clearExpireLoginLogTime', time(), 0);
				}
				//超过一天清除一次超过一个月的日志
				if(time()-$clearTime>86400){
					$time = strtotime('-1 months');
					Yii::app()->writer->lt('runtime', $time)->remove('dld_backlog');
				}
				
				if (!$account->save ()) {
					$logAttributes['sta']=false;
					Yii::app()->backlog->logging($logAttributes,false);
					$passport->setPassportCachedUserDataByName($this->username, $account->getAttributes());
					return UtilD::handleResult ( 0, '登录失败' );
				}
				Yii::app()->backlog->logging($logAttributes,$mflag);
				return UtilD::handleResult ( 1, '登录成功' );
			} else {
				$logAttributes['userid']=0;
				$logAttributes['username']=$this->username;
				Yii::app()->backlog->logging($logAttributes,false);
				return UtilD::handleResult ( 0, '用户名或者密码不正确！' );
			}
		} catch ( Exception $e ) {
			return UtilD::handleResult ( 0, '系统忙，请稍后再试！'.$e->getMessage() );
		}
	}
	
	public function getId() {
		return (int)$this->_identity;
	}

}